package com.itheima.mp.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.Service.UserService;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.enums.UserStatus;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 韩汶锦
 * @date: 2025/4/9
 */
@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public void deduction(Long id, Integer money) {
        User user = getById(id);
        if (user==null || user.getStatus()== UserStatus.FREEZE){
            throw new RuntimeException("用户不存在");
        }
        if (user.getBalance()<money){
            throw new RuntimeException("余额不足");
        }
        Integer balance = user.getBalance()-money;
        lambdaUpdate().
                set(User::getBalance,balance)
                .eq(User::getId,id)
                .set(balance == 0,User::getStatus,2)
                .eq(User::getBalance,user.getBalance())
                .update();
        //baseMapper.deduction(id,money);
    }

    @Override
    public UserVO queryUserAndAddresses(Long id) {
        User user = getById(id);
        if (user==null || user.getStatus()== UserStatus.FREEZE){
            throw new RuntimeException("用户不存在");
        }
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

        List<Address> list = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId,id)
                .list();
        List<AddressVO> list1 = BeanUtil.copyToList(list, AddressVO.class);
        userVO.setAddresses(list1);
                return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressesByIds(List<Long> ids) {
        List<User> users1 = listByIds(ids);

        List<UserVO> users = BeanUtil.copyToList(users1, UserVO.class);
        List<Address> addresses= Db.lambdaQuery(Address.class)
                .in(Address::getUserId,ids)
                .list();
        for (UserVO user : users) {
            List<AddressVO> list= addresses.stream().map(address -> {
                if (user.getId().equals(address.getUserId())) {
                    return BeanUtil.copyProperties(address, AddressVO.class);
                }
                return null;
            }).collect(Collectors.toList());
            user.setAddresses(list);
        }

        return users;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(PageQuery query) {
        // 1.构建条件
        // 1.1.分页条件
        Page<User> page = Page.of(query.getPageNo(), query.getPageSize());
        // 1.2.排序条件
        if (query.getSortBy() != null) {
            page.addOrder(new OrderItem(query.getSortBy(), query.getIsAsc()));
        }else{
            // 默认按照更新时间排序
            page.addOrder(new OrderItem("update_time", false));
        }
        // 2.查询
        page(page);
        // 3.数据非空校验
        List<User> records = page.getRecords();
        if (records == null || records.size() <= 0) {
            // 无数据，返回空结果
            return new PageDTO<>(page.getTotal(), page.getPages(), Collections.emptyList());
        }
        // 4.有数据，转换
        List<UserVO> list = BeanUtil.copyToList(records, UserVO.class);
        // 5.封装返回
        return new PageDTO<UserVO>(page.getTotal(), page.getPages(), list);
    }
}
